package com.netsdk.lht2.rtsp;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CommandTask implements Runnable{
    private final String deviceId;
    private Process process;
    private final String targetRtspUrl;
    private final String note;

    public CommandTask(String deviceId, String note) throws IOException {
        this.deviceId = deviceId;
        this.targetRtspUrl = "http://10.238.138.220:554/stream/"+deviceId;
        this.note = note;
    }

    private void init() throws IOException {
        String rtspUrl = getRtspUrl(deviceId);
        process = execFfmpeg(rtspUrl);
        printInfo(deviceId,process);
    }

    private  String getRtspUrl(String deviceId){
        String url = "http://10.237.218.61:38502/xf-public-api-device-search/v1/stream/live/open";
        String bodyTemplate = "{\n" +
                "\"deviceId\":\"%s\",\n" +
                " \"protocol\":\"rtsp\",\n" +
                "\"resolution\":\"SD\"\n" +
                "}";
        String res = HttpUtil.createPost(url)
//                .header("Authorization","eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJqZHF4bGtzZiIsInVzZXJOYW1lIjoi5ZiJ5a6a5YWo5oGv6Lev5Y-j566X5rOVIiwib3JnSWQiOiLpmYbkvIoiLCJvcmdOYW1lIjoiMTM2NjE3NDM0MzAiLCJjcmVhdGVUaW1lIjoxNzEyNzQ4MDIxMjk5LCJleHAiOjQxMDI0MTYwMDAwMDB9.QfUTPoiC2Vs1SPKu5lgg8qQBgLfSTAEev5bOoH9_ibw")
                .header("Authorization","eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJqcWN5ZHAiLCJ1c2VyTmFtZSI6IuiPiuWbreWfjui_kOWkp-WxjyIsIm9yZ0lkIjoi6ZmG5LyKIiwib3JnTmFtZSI6IjEzNjYxNzQzNDMwIiwiY3JlYXRlVGltZSI6MTY5NTg3ODE4NDUwMiwiZXhwIjo0MTAyNDE2MDAwMDAwfQ.VzbN6kpW2BWXp1QDOTJMia97ne5KIfUoSU_W5V39jN4")
                .header("PERSON-ID","bb198cd2be0679907810418b490b9f12")
                .body(String.format(bodyTemplate, deviceId))
                .execute()
                .body();
        JSONObject jsonObject = JSON.parseObject(res);
        if (jsonObject.getInteger("code")==0){
            return jsonObject.getJSONObject("data").getString("send_uri");
        }else {
            return null;
        }
    }

    private  Process execFfmpeg(String rtspUrl) throws IOException {
        List<String> command = new ArrayList<>();
        command.add("C:\\000\\ffmpeg\\ffmpeg-2024-11-13-git-322b240cea-full_build\\ffmpeg-2024-11-13-git-322b240cea-full_build\\bin\\ffmpeg.exe");
        command.add("-rtsp_transport");
        command.add("tcp");
        command.add("-i");
        command.add(rtspUrl);
        command.add("-c");
        command.add("copy");
        command.add("-f");
        command.add("rtsp");
        command.add(targetRtspUrl);
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        return processBuilder.start();
    }
    private  void  printInfo(String deviceId,Process process){
        InputStream inputStream = process.getErrorStream();
        new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                try {
                    while ((line = reader.readLine()) != null) {
                        System.out.println(deviceId + ": "+ line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    @Override
    public void run() {

        while (true){
            try {
                Thread.sleep(10000);
                init();
                process.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Process getProcess() {
        return process;
    }
}
